package priv.xakml.demo.mysql.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import priv.xakml.demo.mysql.Exceptions.BizException;
import priv.xakml.demo.mysql.Test;
import priv.xakml.demo.mysql.TestItem;
import priv.xakml.demo.mysql.TestItemMapper;
import priv.xakml.demo.mysql.TestMapper;
import priv.xakml.demo.mysql.service.ITestService;

import java.util.List;

/**
 * @author lhx
 * @date 2021-11-18 16:35
 **/
@Service
public class TestService implements ITestService {
    private final TestMapper testMapper;
    private final TestItemMapper testItemMapper;

    @Autowired
    public TestService(TestMapper testMapper,
                       TestItemMapper testItemMapper) {
        this.testMapper = testMapper;
        this.testItemMapper = testItemMapper;
    }

    public List<Test> getAll(){
        return testMapper.selectAllTest();
    }


    /**
     * 保存test数据
     * @param data
     * @return
     */
    @Override
    @Transactional(rollbackFor = BizException.class)
    public boolean insertTestData(priv.xakml.demo.mysql.Test data)
    {
        int rowsAffect = this.testMapper.insertTestData(data);
        System.out.println("主表保存影响到的行数：" + rowsAffect);
        if(data.getId() % 2 == 0)
            throw new BizException("主记录Id为偶数时，自动回滚数据");
        if(rowsAffect > 0 && data.getItems() != null && data.getItems().size() > 0){
            for (TestItem item : data.getItems()){
                item.setTestId(data.getId());
            }
            rowsAffect =  this.testItemMapper.insertTestItemBatch(data.getItems());
            System.out.println("子表保存影响到的行数：" + rowsAffect);

            if(rowsAffect > 0)
                return true;
            else {
                throw new BizException("子表保存失败，保存已撤销");
            }
        }else {
            throw new BizException("主表保存失败，保存已撤销");
        }

    }

    /**
     * 批量保存
     * @param list
     * @return
     */
    public boolean insertBatch(List<Test> list){
        int rowsAffect = this.testMapper.insertBatch(list);
        return rowsAffect > 0;
    }

}
